package com.uyayo.oms.system.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.excelhelper.service.BaseExportExcelService;
import com.uyayo.framework.message.model.Result;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.monitor.entity.SysSession;
import com.uyayo.system.monitor.model.SysSessionCondition;
import com.uyayo.system.monitor.service.SessionsService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 
 * <p>
 * Title: SessionController
 * </p>
 * <p>
 * Description:用户上下线的controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/system/monitor/session")
public class SysSessionMonitorController {

	@Autowired
	@Qualifier("baseExportExcelXSSFService")
	private BaseExportExcelService baseExportExcelService;


	private final SessionsService sessionsService;
	
	private final ParamBiz paramBiz;

	@Autowired
	public SysSessionMonitorController(ParamBiz paramBiz, SessionsService sessionsService) {
		this.paramBiz = paramBiz;
		this.sessionsService = sessionsService;
	}

	@RequestMapping(value="index",method=RequestMethod.GET)
	@MethodName(value="系统管理->系统监控->用户会话监控")
	public String index() throws Exception {
		return paramBiz.getManagerTemplatesPrefix()+"system/monitor/session/index";
	}
	
	@ResponseBody
	@RequestMapping("grid")
	@RequiresPermissions("system:monitor:session:query")
	@MethodName(value="系统管理->系统监控->用户会话监控->查询列表",type=2)
	public  PageResult<SysSession> grid(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第多少行之后开始
                                        @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize, String sort, String order, SysSessionCondition sysSessionCondition) throws Exception {
		PageBean<SysSession> pageBean=new PageBean<>();
		try {
			pageBean = sessionsService.selectSession((start / pageSize) + 1, pageSize,sort,order,sysSessionCondition);
		} catch (Exception e) {
			e.printStackTrace();		
		}
		PageResult<SysSession> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}
	

	/**
	 * 查看
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="系统管理->监控管理->系统事件监控->查看",type=2)
	@RequiresPermissions("system:monitor:session:view")
	public ModelAndView show(ModelAndView modelAndView,String id) {
		SysSession sysSession = new SysSession();
		try {
			sysSession = sessionsService.getSessionById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("sysSession",sysSession);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/monitor/session/view");
		return modelAndView;
	}
	
	/**
	 * 杀死会话
	 */
	/*@ResponseBody
	@RequestMapping("logout")
	@MethodName(value="系统管理->系统监控->用户会话监控->注销用户",type=2)
	public ExtMap session_logout(HttpServletRequest request) {
		String ids = extMap.get("ids").toString();
		String msg = "成功杀死会话";
		if (!StringUtils.isBlank(ids)) {
			String[] idArr = ids.split(",");
			for (int i = 0; i < idArr.length; i++) {
				if (!idArr[i].toString().equalsIgnoreCase(request.getSession().getId())) {
					HttpSession session = OnoffLineListener.getSessionByID(idArr[i].toString());
					if (session!=null) {
						session.invalidate();
						extMap.setSuccess(true);
					}else{
						extMap.setSuccess(false);
						msg = " 提示：选择的用户会话已不存在！";
					}
				} else {
					extMap.setSuccess(false);
					msg = " 提示：不能杀死当前用户会话！";
				}
			}
			extMap.setMsg(msg);
		}else{
			extMap.setSuccess(false);
			extMap.setMsg("提示：请选择要删除的会话！");
		}
		return extMap;
	}*/



	/**
	 * 批量删除记录
	 */
	@ResponseBody
	@RequestMapping("delete")
	@RequiresPermissions("system:monitor:session:delete")
	@MethodName(value="系统管理->系统监控->用户会话监控->删除",type=2)
	public Result deleteSessionMonitor(String ids) {
		try {
			int deleteCount = sessionsService.deleteSessionMonitor(ids);
			if(deleteCount<=0){
				return Result.errorAndMsg("删除失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("删除失败！");
		}
		return Result.successAndMsg("删除成功！");
	}


	@RequestMapping(value = "export")
	@RequiresPermissions("system:monitor:session:export")
	@MethodName(value="系统管理->系统监控->用户会话监控->导出Excel",type=2)
	public ModelAndView exportExcel(HSSFWorkbook workbook, HttpServletResponse response, String sort,String order,SysSessionCondition sysSessionCondition) throws Exception {

		response.setContentType("octets/stream;charset=UTF-8");
		String fileName = new String("用户会话监控".getBytes("UTF-8"),"ISO8859-1");
		response.addHeader("Content-Disposition", "attachment;filename="+fileName+".xls");

		String[] headers = {"会话编号","登录名","ip地址","浏览器类型","登录时间","注销时间"};
		String[] fieldNames = {"code","userLoginname","ip","browser","createdTime","logoutTime"};

		try {

			List<SysSession> sqlList = sessionsService.selectSessionMonitor(sort,order,sysSessionCondition);

			OutputStream out = response.getOutputStream();

			this.baseExportExcelService.exportExcel(workbook,0,"用户会话监控",headers,fieldNames, sqlList, "yyyy-MM-dd HH:mm:ss");

			workbook.write(out);

			out.close();

		} catch (FileNotFoundException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return null;
	}

}
